<!-- 角色管理 -->
<template>
  <div>
    <!-- <el-breadcrumb class="title">
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb> -->
    <div class="tb">
      <div class="search">
        <el-input placeholder="角色名称" v-model="name" clearable> </el-input>
      </div>
      <div class="btn">
        <el-button type="primary" @click="search()">查询</el-button>
        <el-button @click="reset()">重置</el-button>
      </div>
    </div>
    <div class="add">
      <el-button @click="add()">新建角色</el-button>
    </div>
    <div>
      <el-table
        :data="tableData"
        border
        style="width: 100%; height: 600; margin-top: 20px"
        :header-cell-style="{
          background: '#f0f7fe',
          color: '#467ee1',
          fontSize: '16px',
        }"
      >
        <el-table-column
          label="序号"
          align="center"
          width="100"
          min-width="10%"
          type="index"
          :index="sort"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="角色名称"
          min-width="20%"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="status"
          label="状态"
          min-width="20%"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              @change="changeStatus(scope.row)"
              :active-value="0"
              :inactive-value="1"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          min-width="30%"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="20%">
          <template slot-scope="scope">
            <el-button
              @click="handleUpdate(scope.$index, scope.row)"
              size="mini"
              >修改</el-button
            >
            <el-button
              @click="handleDelete(scope.row)"
              type="danger"
              size="mini"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
      >
      </el-pagination>

      <el-dialog
        title="新增/修改角色"
        :visible.sync="dialogTableVisible"
        @close="closed"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="name" label-width="80px">
            <el-input
              v-model="ruleForm.name"
              autocomplete="off"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status" label-width="80px">
            <el-switch
              v-model="ruleForm.status"
              :active-value="0"
              :inactive-value="1"
            ></el-switch>
          </el-form-item>
          <el-form-item label="关联资源" prop="resources" label-width="80px">
            <el-tree
              ref="treeNode"
              :data="treeData"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              default-expand-all
              @check-change="checkedChange"
            >
            </el-tree>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getRole,
  deleteRole,
  addRole,
  getAllResources,
  updataRole,
  getRoleDetail,
} from "@/api/role.js";

export default {
  data() {
    return {
      name: "", //角色名称
      tableData: [], //角色数据
      dialogTableVisible: false, //新增弹出框
      resourcesId: [],
      ruleForm: {
        name: "",
        status: 0,
        resources: [],
      },
      rules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, message: "长度在 2 个字符以上", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        resources: [{ required: true, message: "请选择资源", trigger: "blur" }],
      },
      // resource: [], //资源列表
      currentPage: 1, //目标页码
      pageSize: 10, //显示条数
      totalItems: 0, //总条数
      roleId: "", //修改的角色id
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },

  methods: {
    // 表格序号排序
    sort(index) {
      // index索引从零开始，index +1 即为当前数据序号
      this.currentPage <= 0 ? (this.currentPage = 1) : this.currentPage;
      // 如果当前不是第一页数据
      if (this.currentPage != 1) {
        // index + 1 + (( 当前页 - 1) * 每页展示条数)
        // 比如是第二页数据 1 + ((2 - 1)*5) = 6,第二页数据也就是从序号6开始
        return index + 1 + (this.currentPage - 1) * this.pageSize;
      }
      // 否则直接返回索引+1作为序号
      return index + 1;
    },

    // 查询按钮
    search() {
      this.getData();
    },

    // 重置
    reset() {
      this.name = "";
      this.getData();
    },

    // 新增/修改角色
    add() {
      if (this.$refs["ruleForm"] !== undefined) {
        this.$refs["ruleForm"].resetFields();
      }
      this.dialogTableVisible = true;
    },

    // 修改状态
    changeStatus(row) {
      updataRole({
        id: row.id,
        status: row.status,
      }).then((res) => {
        if (res.data.status == 200) {
          this.getData();
        }
      });
    },

    closed() {
      if (this.$refs["treeNode"] !== undefined) {
        this.$refs.treeNode.setCheckedKeys([]);
      }
    },

    // 修改操作
    handleUpdate(index, row) {
      // console.log(index, row);
      this.dialogTableVisible = true;
      getRoleDetail(row.id).then((res) => {
        this.$refs.treeNode.setCheckedKeys([]);
        const formData = res.data.data;
        // console.log(formData);
        this.ruleForm.name = formData.name;
        this.ruleForm.status = formData.status;
        // console.log(formData.resourcesIds);
        if (formData.resourcesIds) {
          formData.resourcesIds.forEach((item) => {
            let node = this.$refs.treeNode.getNode(item);
            if (node.isLeaf) {
              this.$refs.treeNode.setChecked(node, true);
            }
          });
          // this.$refs.treeNode.setCheckedKeys(formData.resourcesIds);
        }
        this.roleId = row.id;
      });
    },

    // 删除操作
    handleDelete(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRole(row.id).then((res) => {
            if (res.data.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 修改每页展示的条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getData();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.getData();
    },

    checkedChange() {
      this.ruleForm.resources = this.$refs.treeNode.getCheckedKeys();
      let getHalfCheckedKeys = this.$refs.treeNode.getHalfCheckedKeys();
      getHalfCheckedKeys.forEach((item) => {
        this.ruleForm.resources.push(item);
      });
      // console.log(this.ruleForm.resources);
    },

    // 新增/修改角色提交
    submitForm() {
      // console.log(this.ruleForm.resources);
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 新增操作;
          if (!this.roleId) {
            // console.log(this.ruleForm);
            addRole(this.ruleForm).then((res) => {
              if (res.data.status == 200) {
                this.dialogTableVisible = false;
                this.$message({
                  type: "success",
                  message: "添加成功",
                });
                this.getData();
              }
            });
          }
          // 修改操作
          if (this.roleId) {
            updataRole({
              id: this.roleId,
              name: this.ruleForm.name,
              status: this.ruleForm.status,
              resources: this.ruleForm.resources,
            }).then((res) => {
              this.ruleForm.status = true;
              if (res.data.status == 200) {
                this.dialogTableVisible = false;
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
                this.getData();
                this.roleId = "";
              }
            });
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },

    // 获取表单数据
    getData() {
      getRole({
        name: this.name,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      }).then((res) => {
        const roleData = res.data.data.roleList;
        this.tableData = roleData;
        this.totalItems = res.data.data.total;
      });
    },

    // 获取所有关联资源
    getResources() {
      getAllResources().then((res) => {
        // this.resource = res.data.data;
        this.treeData = res.data.data;
        // console.log(this.treeData);
      });
    },
  },
  mounted() {
    this.getData();
    this.getResources();
  },
};
</script>
<style lang="scss" scoped>
.select {
  height: 50px;
  line-height: 50px;
  text-align: right;
}

.title {
  height: 50px;
  line-height: 50px;
  background-color: #f9f9f9;
  border: 1px solid #e9e9e9;
  border-radius: 5px;
  font-size: 17px;
  font-weight: bolder;
  padding: 0 20px;
}

.tb {
  display: flex;
  justify-content: flex-start;
  padding: 20px 0 20px 0;
  box-sizing: border-box;

  .search {
    margin-right: 20px;

    .el-input {
      width: 200px;
    }
  }

  .btn {
    width: 200px;
  }
}

.add {
  width: 280px;
}

.el-pagination {
  margin: 25px 0;
}

:deep(.el-pager li.active) {
  color: #ffffff;
  background-color: #409eff;
}

:deep(.el-pager li:hover) {
  color: #787d83;
}
</style>
